<template>
    <div class="chatBoard">
                <div class="roleRegionA">
                    <el-avatar class="Avatar" :size="100" shape="circle" src="/systemImage/Immortality.png"></el-avatar>
                    <span class="Name">{{ conversationInformation?.AI_role }}</span>
                    <div class="AIstatus">
                        <div class="statusIcon"></div>
                        
                            <template v-if="useConversationStore().isLoading">
                                <span class="statusText">
                                    思考中
                                </span>
                            </template>
                            <template v-else>
                                <span class="statusText">
                                    在线
                                </span>
                            </template>
                        
                    </div>
                    <div class="roleFunction"></div>
                </div>
                <div class="chatContent" ref="chatContainer">
                    <span class="tipInformation">
                        <el-icon class="bigIcon"><CaretLeft /></el-icon>
                        <el-icon class="bigIcon"><CaretLeft /></el-icon>
                        <el-icon class="bigIcon"><CaretLeft /></el-icon>
                        您于 {{formatTime(new Date(conversationInformation?.created_at as Date))}} 与{{ conversationInformation?.AI_role }}取得联系
                        <el-icon class="bigIcon"><CaretRight /></el-icon class="bigIcon">
                        <el-icon class="bigIcon"><CaretRight /></el-icon>
                        <el-icon class="bigIcon"><CaretRight /></el-icon>
                    </span>
                    <template v-for="dialog in allDialog" :key="dialog.id">
                        <template v-if="allDialog && allDialog.indexOf(dialog)>0 && DialogDateDelayCheck(dialog,allDialog[allDialog?.indexOf(dialog)-1])">
                            <span class="tipInformation" style="font-size: 60%; opacity: 0.5;">

                                {{ formatTime(new Date(dialog.send_time)) }}

                            </span>
                        </template>
                        <dialogBoard :sender="dialog.sender==='user' ? true : false" :value="dialog.content"></dialogBoard>
                    </template>
                    <AIThinking v-show="useConversationStore().isLoading"/>
                    
                </div>
                <div class="roleRegionB">
                    <div class="options"></div>
                    <el-avatar class="Avatar" :size="100" shape="circle" ></el-avatar>
                </div>
                <div class="chatInputBoard">
                    <textarea v-model="chatContent" class="textRegion" name="chatContent" id="1" ></textarea>
                    <div class="optionRegion">
                        <button class="classButton"  type="submit" @click="ARS()">语音</button>
                        <button class="classButton"  type="submit" @click="submitMyDialog()">发送</button>
                    </div>
                </div>
            </div>
    <div class="ASRContainer">
        <div class="microIcon">
            <el-icon><Microphone /></el-icon>
        </div>
        <div class="microOptions">
            <el-icon id="submitButton" @click="ARS()"><VideoPause /></el-icon>
            <el-icon id="audioButton"><VideoPlay /></el-icon>
        </div>
        <div class="microDisplayCard">

        </div>
    </div>
</template>

<script lang="ts" setup>
import {nextTick, ref, watch} from 'vue'
import request from '../../utils/request';
import {useRoute} from 'vue-router'
import formatTime from '../../utils/dateTransform';
import { ElMessage } from 'element-plus';
import { useConversationStore } from '../../stores/conversationStore';
import audioManager from '../../utils/AudioManager';


interface conversationInfo{
    id:number,
    user_id:number,
    AI_role:string,
    created_at:Date,
    latestChat:Date
}

interface dialog{
    id:number,
    conversation_id:number,
    sender:'user'|'assistant',
    content:string,
    send_time:string,
}

const route = useRoute();
const chatContainer=ref()
const chatContent=ref('')
let mediaRecorder:MediaRecorder | null = null;
let audioChunk=[];
const audioButton=document.getElementById('audioButton') as HTMLButtonElement
const submitButton=document.getElementById('submitButton') as HTMLButtonElement

let conversationInformation=ref<conversationInfo>()
let allDialog=ref<dialog[]>()

updateConversationDetail();

function DialogDateDelayCheck(currentDialog:dialog,lastDialog:dialog | undefined):boolean{
    if(lastDialog){
        const currentTime=new Date(currentDialog.send_time);
        const lastTime=new Date(lastDialog.send_time);
        const delay =currentTime.getTime()-lastTime.getTime();
        if(delay/1000/60>=20){
            return true
        }else{
            return false
        }
    }else{
        return false
    }
}

async function updateConversationDetail(){
    try{
        conversationInformation.value = await request.get(`/api/deepSeek/conversation/${route.params.id}`);
        allDialog.value = await request.get(`/api/deepSeek/dialogHistory`,{id:route.params.id});
    }catch(error){
        console.error(error)
    }
}

watch(()=>route.params.id,
    (newVal,oldVal)=>{
        updateConversationDetail();
    }
)

async function submitMyDialog(){
    try{
        if(chatContent.value===''){
            ElMessage.warning('请勿发送空内容')
        }

        const currentHeight1 = chatContainer.value.offsetHeight;
        useConversationStore().isLoading=true;
        await nextTick();
        const newHeight1 = chatContainer.value.offsetHeight;
        chatContainer.value.style.height = `${currentHeight1}px`;
        chatContainer.value.offsetHeight;
        chatContainer.value.style.height = `${newHeight1}px`;
        chatContainer.value.scrollTop=chatContainer.value.scrollHeight;
        const AIreply = await request.post('api/deepSeek/dialog',{conversationId:route.params.id,userMessage:chatContent.value});
        chatContent.value='';
        useConversationStore().isLoading=false;
        const currentHeight2 = chatContainer.value.offsetHeight;
        allDialog.value = await request.get(`/api/deepSeek/dialogHistory`,{id:route.params.id});
        await nextTick();
        const newHeight2 = chatContainer.value.offsetHeight;
        chatContainer.value.style.height = `${currentHeight2}px`;
        chatContainer.value.offsetHeight;
        chatContainer.value.style.height = `${newHeight2}px`;
        chatContainer.value.scrollTop=chatContainer.value.scrollHeight;
        //可优化：选择是否在消息发送后自动播放语音
        audioManager.play(AIreply.content);
        
    }catch(error){
        return console.error(error)
    }
}

async function ARS() {
    try{
        const micStream =await navigator.mediaDevices.getUserMedia({audio:true});
        mediaRecorder = new MediaRecorder(micStream);

        mediaRecorder.ondataavailable = function(e){
            if(e.data.size>0){
                audioChunk.push(e.data);
            }
        }

        mediaRecorder.start();
        audioChunk=[];
        audioButton.disabled =true;
        submitButton.disabled=false;
        
    }catch(error){
        console.log(error);
    }
}

</script>

<style>
@keyframes onRender {
  to {
    opacity: 1;
  }
}
</style>

<style scoped>
.ASRContainer{
    background-color: rgb(0, 0, 0,0.6);
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    width: 20%;
    height: 50%;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 5fr 1fr 1fr;
    grid-template-areas: 
    "iconRegion iconRegion iconRegion"
    "optionRegion optionRegion optionRegion"
    "informationRegion informationRegion informationRegion";
    gap: 1px;
    border-radius: 15px;
}

.microIcon{
    grid-area: iconRegion;
    width: 100%;
    height: 100%;
    font-size: 800%;
    display:flex;
    justify-content: center;
    align-items: center;
    color: rgb(255, 255, 255,0.7);
}

.microOptions{
    grid-area: optionRegion;
    width: 100%;
    height: 100%;
    font-size: 200%;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 30%;
    color: rgb(255, 255, 255,0.9);
}

.microDisplayCard{
    grid-area: informationRegion;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.tipInformation{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    margin-top: 20px;
    margin-bottom: 10px;
    color: rgb(0,0,0,0.7);
    font-size: 90%;
    font-weight: 500;
}

.bigIcon{
    font-size: 120%;
}

.chatBoard{
    width: 100%;
    height: 100%;
    display: grid;
    grid-template-columns: 1fr 5fr 1fr;
    grid-template-rows: 5fr 2fr;
    grid-template-areas: 
    "roleRegionA chatContent roleRegionB"
    "roleRegionA chatInputBoard roleRegionB";
    
}

.roleRegionA{
    grid-area: roleRegionA;
    background-color: rgba(255, 255, 255, 0.7);
    border-right: 1px solid rgb(0, 0, 0,0.5);
    display: flex;
    flex-direction: column;
    justify-content: left;
    align-items: center;
    overflow: hidden;

}

.roleRegionB{
    grid-area: roleRegionB;
    background-color: rgba(255, 255, 255, 0.7);
    border-left: 1px solid rgb(0, 0, 0,0.2);
    display: flex;
    flex-direction: column;
    justify-content: right;
    align-items: center;
}

.chatContent{
    grid-area: chatContent;
    background-color: rgba(255, 255, 255, 0.7);
    display: flex;
    flex-direction: column;
    justify-content: left;
    max-height: 100%;
    overflow: auto;
    transition: all 0.5s ease;
}



.chatInputBoard{
    grid-area: chatInputBoard;
    border-top: 1px solid rgb(0, 0, 0,0.1);
    background-color: rgba(255, 255, 255, 0.7);
    display: flex;
    flex-direction: column;
    align-items: center;

}

.Avatar{
    margin-top: 20px;
    margin-bottom: 20px;
    background-color: rgb(0, 0, 0,0.8);
}

.Name{

    font-weight: 600;
    font-size: 100%;
    width: 90%;
    color: rgb(0, 0, 0,0.7);
    flex-shrink: 1;
    display: inline-block;
    text-align: center;
    justify-content: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.AIstatus{
    flex: 1;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

}

.statusIcon{
    width: 12px;
    height: 12px;
    background-color: rgb(0, 255, 0);
    border-radius: 100%;
}

.statusText{
    margin: 5px;
    font-size: 60%;
    font-weight: 500;
    color: rgb(0, 0, 0,0.6);

    opacity: 0;
    animation: onRender 1s 0.1s forwards
}


.roleFunction{
    flex: 9;
    width: 100%;
}

.options{
    width: 100%;
    flex:1;
}

.textRegion{
    width: 98%;
    height: 60%;
    background: rgb(255, 255, 255,0.6);
    margin: 10px;
    border-radius: 5px;
    padding: 5px;
    outline: none;
    resize: none;
    border: 0 solid ;
    font-size: 90%;
    font-family: Arial, Helvetica, sans-serif;
    color: rgb(0, 0, 0,0.95);
}

.optionRegion{
    width: 98%;
    flex: 1;
    margin: 10px;
    display: flex;
    align-items: center;
    justify-content: right;
}

.classButton{
    width: 10%;
    height: 98%;
    margin: 5px;
    cursor: pointer;
}
</style>